<?php
define('IN_SYS', true);
require '../framework/bootstrap.inc.php';
require IA_ROOT . '/web/common/bootstrap.sys.inc.php';

load()->func('logging');
logging_run(json_encode($_GPC));
$token = 'Z4Ocfbk0XwJZlqCZ';
$group_id = 2;      //平台默认的组

if($_GPC['__input']['action'] == 'verifyInterface')
{
    $signature = $_GPC['signature'];
    $timestamp = $_GPC['timestamp'];
    $eventId = $_GPC['eventId'];
    if(checkSignature($signature, $token, $timestamp, $eventId)){
        print_r(json_encode(array('echoback'=> $_GPC['__input']['echoback'])));
        exit;
    }
}
if($_GPC['__input']['action'] == 'createInstance')
{
    $openid = $_GPC['__input']['openId'];
    $productid = $_GPC['__input']['productId'];
    $mobile = $_GPC['__input']['mobile'];

    $user_bind_info = pdo_fetch("SELECT * FROM ".tablename('users_bind')." WHERE bind_sign = :bind_sign AND third_type = 4 LIMIT 1", array(':bind_sign' => $openid));
    $uid = $user_bind_info['uid'];

    if(empty($user_bind_info))
    {
        //获取用户注册信息
        $register = create_user_api($openid);
        $member['status'] = !empty($_W['setting']['register']['verify']) ? 1 : 2;
        $member['remark'] = '';
        $member['groupid'] = $group_id;
        /*if (empty($member['groupid'])) {
            $member['groupid'] = pdo_fetchcolumn('SELECT id FROM '.tablename('users_group').' ORDER BY id ASC LIMIT 1');
            $member['groupid'] = intval($member['groupid']);
        }*/
        $group = user_group_detail_info_api($member['groupid']);
        $timelimit = intval($group['timelimit']);
        if($timelimit > 0) {
            $member['endtime'] = strtotime($timelimit . ' days');
        }
        $member['starttime'] = time();
        if (!empty($owner_uid)) {
            $member['owner_uid'] = pdo_getcolumn('users', array('uid' => $owner_uid, 'founder_groupid' => 2), 'uid');
        }

        $user_id = user_register_api($member);
        $username = $mobile;
        $password = $register['member']['password'];
        pdo_update('users', array('username' => $username), array('uid' => $user_id));
        if($user_id > 0) {
            unset($member['password']);
            $member['uid'] = $user_id;
            if (!empty($profile)) {
                $profile['uid'] = $user_id;
                $profile['createtime'] = time();
                pdo_insert('users_profile', $profile);
            }
            pdo_insert('users_bind', array('uid' => $user_id, 'bind_sign' => $member['openid'], 'third_type' => $member['register_type'], 'third_nickname' => $member['username']));
        }
        $uid = $user_id;
    }
    if($uid == 0 || $uid < 0)
    {
        $return_array = array(
            'signId'=> 0
        );
    }
    else
    {
        $group = pdo_fetch("SELECT * FROM ".tablename('users_group')." WHERE id = :id LIMIT 1", array(':id' => $group_id));
        if(empty($group))
        {
            $return_array = array(
                'signId'=> 0
            );
        }
        else
        {
            $data = array(
                'groupid' => $group['id']
            );
            pdo_update('users', $data, array('uid' => $uid));
            $acInfo = '账号:'.$username.',密码:'.$password;
            $return_array = array(
                'signId'=> GetRandStr(11),
                'appInfo'=> array(
                    'website'=>$_W['siteroot'] . 'web/index.php'
                ),

                'additionalInfo' => array(
                    array(
                        'name' => '账号信息',
                        'value' => $acInfo
                    ),
                    array(
                        'name' => '登录网址',
                        'value' => 'https://www.taoanli.cn'
                    ),
                    array(
                        'name' => '专属客服',
                        'value' => '微信号:t840111266,电话:18610063455'
                    ),
                    array(
                        'name' => '温馨提示',
                        'value' => '登录后请尽快修改密码,使用教程:http://help.itlian.vip/help/604692,如需帮助请联系客服人员。'
                    ),
                ),
            );
        }
        logging_run('用户信息'.json_encode($group));
    }
    print_r(json_encode($return_array));
    exit;
}

function create_user_api($openid)
{
    $user = array();
    $profile = array();
    $user['username'] = 'admin2';
//    $user['username'] = 'mq'.uniqid().rand(1111,9999);
//    $user['password'] = rand(211111,999999);
    $user['password'] = '35862763';
    $user['type'] = 1;
    $user['starttime'] = time();
    $user['openid'] = $openid;
    $user['register_type'] = 4;

    $profile['avatar'] = '';
    $profile['nickname'] = '';
    $profile['gender'] = 1;
    $profile['resideprovince'] = '';
    $profile['residecity'] = '';
    $profile['birthyear'] = '';

    return array(
        'member' => $user,
        'profile' => $profile
    );
}
function user_group_detail_info_api($groupid = 0) {
    $group_info = array();

    $groupid = is_array($groupid) ? 0 : intval($groupid);
    if(empty($groupid)) {
        return $group_info;
    }
    $group_info = pdo_get('users_group', array('id' => $groupid));
    if (empty($group_info)) {
        return $group_info;
    }

    $group_info['package'] = (array)iunserializer($group_info['package']);

    return $group_info;
}
function user_register_api($user) {
    if (empty($user) || !is_array($user)) {
        return 0;
    }
    if (isset($user['uid'])) {
        unset($user['uid']);
    }
    $user['salt'] = 'MVA78qTr';
    $user['password'] = '6596148b014241f98157a580e7920ddb05cbe0fc';
    $user['joinip'] = '';
    $user['joindate'] = time();
    $user['lastip'] = '';
    $user['lastvisit'] = time();
    if (empty($user['status'])) {
        $user['status'] = 2;
    }
    if (empty($user['type'])) {
        $user['type'] = 1;
    }
    $result = pdo_insert('users', $user);
    if (!empty($result)) {
        $user['uid'] = pdo_insertid();
    }

    return intval($user['uid']);
}


function user_hash_api($passwordinput, $salt) {

    global $_W;

    $passwordinput = "{$passwordinput}-{$salt}-{$_W['config']['setting']['authkey']}";

    return sha1($passwordinput);

}

function GetRandStr($len)
{
    $chars_array = array(
        "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z",
    );
    $charsLen = count($chars_array) - 1;

    $outputstr = "";
    for ($i=0; $i<$len; $i++)
    {
        $outputstr .= $chars_array[mt_rand(0, $charsLen)];
    }
    return $outputstr;
}

function checkSignature($signature, $token, $timestamp, $eventId)
{
    $currentTimestamp = time();
    if ($currentTimestamp - $timestamp > 30) {
        return false;
    }
    $timestamp = (string)$timestamp;
    $eventId = (string)$eventId;
    $params = array($token, $timestamp, $eventId);
    sort($params, SORT_STRING);
    $str = implode('', $params);
    $requestSignature = hash('sha256', $str);
    return $signature === $requestSignature;
}

?>